import { phoneNumberReg, specialCharReg, zhReg } from '@/utils/utils';
import { ModalForm, ProFormSelect, ProFormText } from '@ant-design/pro-components';
import type { FormInstance } from 'antd';
import { message } from 'antd';
import type { UpdateUserType, UserTableListItem } from '../types';
import { useRef } from 'react';
import { useState } from 'react';
import { queryCompanies, updateUser } from '../service';
import { Role } from '@/utils/types.d';
import { useModel } from 'umi';

export default (props: { func: () => void; user: UserTableListItem }) => {
  const { initialState } = useModel('@@initialState');
  const currUser = initialState?.currentUser;
  const { func, user } = props;
  const formRef = useRef<FormInstance>();
  const [defaultName, setDefaultName] = useState<string>(user.userName);
  const [defaultPhoneNum, setDefaultPhoneNum] = useState<string>(user.phoneNumber);
  return (
    <ModalForm<UpdateUserType>
      title="修改用户"
      layout="horizontal"
      width="40vw"
      modalProps={{
        destroyOnClose: true,
      }}
      formRef={formRef}
      labelCol={{ span: 6 }}
      wrapperCol={{ span: 14 }}
      trigger={<a>修改</a>}
      onFinish={async (values) => {
        const res = await updateUser(user._id, values);
        if (res.success) {
          if (values.userName) setDefaultName(values.userName);
          if (values.phoneNumber) setDefaultPhoneNum(values.phoneNumber);
          message.success({ content: res.message, key: 'update_user' });
          func();
          return true;
        }
        message.error({ content: res.message, key: 'update_user' });
        return false;
      }}
    >
      <ProFormText
        required
        label="用户名称"
        placeholder="请输入用户名称(企业管理员请输入企业名称)"
        name="userName"
        initialValue={defaultName}
        rules={[
          {
            validator: (_, val) => {
              if (!val || val.length < 2)
                return Promise.reject(new Error('用户名称长度不得低于2位'));
              if (specialCharReg.test(val))
                return Promise.reject(new Error('用户名称不符合规范，不支持包含特殊字符'));
              return Promise.resolve(val);
            },
          },
        ]}
      />
      <ProFormText required disabled label="用户账号" name="account" initialValue={user.account} />
      {user.role !== Role.ADMIN && (
        <ProFormSelect
          disabled={user.role <= Role.ENTERPRISE}
          name="ownerId"
          label="归属公司"
          debounceTime={300}
          initialValue={user.ownerId}
          request={(val) => queryCompanies(val.keyWords || currUser?.ownerName, false)}
        />
      )}
      {(currUser?.role === Role.ADMIN ||
        (user.role >= currUser?.role && user._id !== currUser?.id)) && (
        <ProFormText.Password
          label="登录密码"
          placeholder="设置登录密码"
          name="password"
          initialValue={undefined}
          rules={[
            {
              validator: (_, val) => {
                if (zhReg.test(val)) return Promise.reject(new Error('登录密码不符合要求'));
                if (val && val.length < 6)
                  return Promise.reject(new Error('用户密码长度不得低于6位'));
                if (val === '123456') return Promise.reject(new Error('密码强度过低'));
                return Promise.resolve(val);
              },
            },
          ]}
        />
      )}
      <ProFormText
        name="phoneNumber"
        initialValue={defaultPhoneNum}
        label="手机号码"
        placeholder="请输入手机号"
        rules={[
          {
            validator: (_, val) => {
              if (val && !phoneNumberReg.test(val))
                return Promise.reject(new Error('手机号不符合规范'));
              return Promise.resolve(val);
            },
          },
        ]}
      />
    </ModalForm>
  );
};
